# coding=utf-8
'''
双向通信Socket之服务器端
    读取客户端发送的数据，将内容输出到控制台
    将控制台输入的信息发送给客户器端
'''
from socket import *
from threading import Thread


def recv_data():
    while True:
        # 读取客户端的消息
        recv_data = client_socket.recv(1024)  # 最大接收1024字节
        recv_content = recv_data.decode('gbk')
        # 将消息输出到控制台
        print(f"客户端说：{recv_content},来自:{client_info}")
        if recv_content == "end":
            print("结束接收消息！")
            break


def send_data():
    while True:
        # 获取控制台信息
        msg = input(">")
        client_socket.send(msg.encode('gbk'))
        if msg == "end":
            print("结束发送消息！")
            break


if __name__ == '__main__':
    # 创建Socket对象
    server_socket = socket(AF_INET, SOCK_STREAM)  # 创建TCP类型的套接字
    # 绑定端口
    server_socket.bind(("127.0.0.1", 8899))  # 本机监听8899端口
    # 监听客户端的连接
    server_socket.listen(5)
    print("等待接收连接！")
    # 接收客户端连接
    client_socket, client_info = server_socket.accept()
    print("一个客户端建立成功")

    t1 = Thread(target=recv_data)
    t2 = Thread(target=send_data)
    t1.start()
    t2.start()
    t1.join()
    t2.join()

    client_socket.close()
    server_socket.close()
